package cn.dt.ymcc.mq;

import cn.dt.ymcc.GlobalException;
import cn.dt.ymcc.domain.Course;
import cn.dt.ymcc.domain.MessageSms;
import cn.dt.ymcc.service.IMessageSmsService;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.util.Date;

@Component
@RocketMQMessageListener(consumerGroup = "service-common-emailmessage-consumer",
        //Topic
        topic = "course-topic",
        //TAGS
        selectorExpression = "course-tags"
)
@Slf4j
public class EmailMessageMQConsumer implements RocketMQListener<MessageExt> {
    @Autowired
    private IMessageSmsService messageSmsService;
    @Override
    public void onMessage(MessageExt message) {
        try {
            String bodyStr = new String(message.getBody(), StandardCharsets.UTF_8);
            Course course  = JSON.parseObject(bodyStr, Course.class);
            MessageSms messageSms = new MessageSms();
            messageSms.setTitle("课程发布");
            messageSms.setContent("亲爱的用户您好，最新课程 <a href='测试'> 测试 </a> 发布啦，点击课程了解详情"+course.getName());
            messageSms.setSendTime(new Date());
            messageSms.setState(1);
            //1.保持数据到数据库
            messageSmsService.insert(messageSms);
            //2.发送邮件
            log.info("亲爱的用户您好，最新课程 <a href='测试'> 测试 </a> 发布啦，点击课程了解详情"+course.getName());
        } catch (Exception e) {
            e.printStackTrace();
            //通过异常来决定ACK
            throw new GlobalException("邮件发送失败");
        }
    }
}
